package com.etymgiko.lyricshere.web.admin;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.etymgiko.lyricshere.SettingsProvider;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.users.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Ivan Holub
 */
public class UserAuthorizationInterceptor extends HandlerInterceptorAdapter {

    private SettingsProvider settingsProvider;

    public void setSettingsProvider(SettingsProvider settingsProvider) {
        this.settingsProvider = settingsProvider;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        if (user != null && settingsProvider.isAdmin(user.getEmail())) {
            return true;
        }
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }
}
